﻿using System.IO;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NHibernate;
using NHibernate.Cfg;
using NCS;
using System.Drawing.Printing;
using System.Threading;
namespace NCS_CS
{

    internal partial class frmMain : System.Windows.Forms.Form
    {
        public static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //DataGridViewPrinter datagrid1Printer;
        public SortableBindingList2<NCS.sample> samples;
        CTP ctp1;
        private Font printFont;
        //int jqcount;
        const string AVESTR = "select * from sampleave" + " where sampleid in (select * from tmpid) order by mdate";
        const string SAMPLESTR = "select * from sample" + " where sampleid in (select * from tmpid) order by sampleid,mdate";
        public NCS.sample sample1;
        private JF2 jf1;
        public Sig mysig;
        bool firstp;
        public void FromMethodReturn()
        {
            this.Show();
            //ModMain.gDb.myLoadmethodByid((ModMain.user1.mname), (ModMain.user1.methodid));
            //ModMain.gDb.saveUser(ref ModMain.user1);
            //if (ModMain.method1 == null)
            //{
            //}
            //else
            //{
                csy1.setmethodpara();
                this.displayMethod();
            //}
        }

        public void changeMethod_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            showfrmMethod();
        }
        private void showfrmMethod()
        {
            this.Hide();
            //if (ModMain.getFrmMethod() == null) { ModMain.getFrmMethod()  = new FrmMethod(); } 
            ModMain.getFrmMethod().Show();

        }
        public void displayMethod()
        {
            if (ModMain.method1 == null)
            {
                this.methodStatus.Text = "用户:" + ModMain.user1.mname + ",方法:" + "";
            }
            else
            {
                this.methodStatus.Text = "用户:" + ModMain.user1.mname + ",方法:" + ModMain.method1.cname;
            }

        }

        private void Check1_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            if (Check1.CheckState == CheckState.Checked)
            {
                ModMain.user1.autoweight = true;
            }
            else
            {
            }
            ModMain.gDb.saveUser(ref ModMain.user1);

            if (Check1.CheckState == CheckState.Checked)
            {
                ctp1.startit();
            }
            else
            {
                ctp1.stopit();
            }
        }

        private void Check7_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            if (Check7.CheckState == CheckState.Checked)
                mcurve1.setshowpeak(true);
            else
                mcurve1.setshowpeak(false);
        }

        private void delrec()
        {
            ModMain.busy = true;
            try
            {
                DialogResult v = default(DialogResult);
                v = MessageBox.Show(this,"确实删除？","",MessageBoxButtons.YesNo );
                if (v != DialogResult.Yes )
                    return;
                //int sid = 0;
                int id = 0;
                //sid = (int)DataGrid1.CurrentRow.Cells["sampleid"].Value;
                id = (int)DataGrid1.CurrentRow.Cells["id"].Value;
                ModMain.gDb.delsig(id);
                ISession session = ModMain.getsession();
                NCS.sample s = null;
                s = (NCS.sample)session.Get(typeof(NCS.sample), id);
                session.Delete(s);
                session.Flush();
                //ModMain.gDb.delaveOne(sid);
                //ModMain.gDb.insertAveOne(sid);
                //NCS.SampleAve ave = (NCS.SampleAve)session.Get(typeof(NCS.SampleAve), sid);
                //if (ave != null)
                //{
                //    session.Refresh(ave);
                //}
                this.refreshSelSample();
                ModMain.busy = false;
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
                ModMain.busy = false;
            }
        }

        private void avgrec()
        {
                ModMain.busy = true;
                string sname = null;
                if (DataGrid1.SelectedRows.Count > 0)
                {
                    MyInputBox tmpd = new MyInputBox("样品名称", (string)DataGrid1.SelectedRows[0].Cells["name"].Value);
                    tmpd.ShowDialog();
                    sname = tmpd.s;
                    if (string.IsNullOrEmpty(sname))
                        return;
                }
                else
                {
                    MessageBox.Show("请选择单次数据", "");
                    return;
                }
                int newSampleid = ModMain.nextSampleId();
            ISession session = ModMain.getsession();
            ITransaction t = session.BeginTransaction();
            try
            {
                foreach (System.Windows.Forms.DataGridViewRow r1 in DataGrid1.SelectedRows)
                {
                    NCS.sample s1 = (NCS.sample)r1.DataBoundItem;
                    s1.sampleid = newSampleid;
                    s1.name = sname;
                    session.Update(s1);
                }
                session.Flush();
                t.Commit();
            }
            catch (System.Exception e1)
            {
                t.Rollback();
            }
            finally{
                session.Close();
                session.Dispose();
            }
            insertOneid(newSampleid);
            refreshSelSample();
            this.SplitContainer_result.Panel2Collapsed = false;
            ModMain.busy = false;
            return;
        }
        //public void delAveOne( int id)
        //{
        //    ModMain.gDb.delaveOne(id);
        //}
        //public void addAVeOne( int id)
        //{
        //    ModMain.gDb.insertAveOne(id);
        //}
        private void CommandStart_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                statusError.Text = "";
                mysig = new Sig();
                sample1 = new NCS.sample();
                firstp = true;
                setRun();
                if (ModMain.method1 == null)
                {
                    modLog.savelogmsg("no method");
                    modLog.showLog();
                    return;
                }
                sample1.weight = Conversion.Val(TextSampleWeight.Text);
                sample1.wlweight = Conversion.Val(Text4.Text);
                if (sample1.weight <= 0)
                {
                    if (ModMain.csystate == Mcsy.csyState.enmSync )//ModMain.SYNC)
                    {
                        TextSampleWeight.Text = ".5";
                        sample1.weight = 1F;
                    }
                    else
                    {
                        MessageBox.Show("质量不能为0!", "");
                        reset_Renamed();
                        return;
                    }
                }
                sample1.name = TextSampleName.Text;
                mcurve1.reset(); 
                mcurve1.setLineCount(5);
                int i = 0;
                for (i = 0; i <= 3; i++)
                {
                    if (ModMain.getChanelEnable(i) == false)
                    {
                        mcurve1.setlinevisible(i, false);
                        setChanelCheck(i, false);
                    }
                    else
                    {
                        mcurve1.setlinevisible(i, true);
                        setChanelCheck(i, true);
                    }
                }
                this.setlineColor();
                //isstart = true;
                firstp = true;
                //firsts = true;
                //stime = myTimer()
                csy1.startCsy();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
                reset_Renamed();
            }
        }
        public void setChanelCheck(int i, bool b)
        {
            switch (i)
            {
                case 0:
                    Check2.Checked = b;
                    break;
                case 1:
                    Check3.Checked = b;
                    break;
                case 2:
                    Check4.Checked = b;
                    break;
                case 3:
                    Check5.Checked = b;
                    break;
            }
        }
        public void setRun()
        {
            //Timer1.Enabled = False
            //TimerJieqi.Enabled = False
            this.hider1.IsReduced = false;
            CommandWeight.Enabled = false;
            ModMain.busy = true;
            ctp1.stopit();
            Check2.CheckState = System.Windows.Forms.CheckState.Checked;
            Check3.CheckState = System.Windows.Forms.CheckState.Checked;
            Check4.CheckState = System.Windows.Forms.CheckState.Checked;
            Check5.CheckState = System.Windows.Forms.CheckState.Checked;
            CommandStart.Enabled = false;
            CommandStop.Enabled = true;
            this.Label1.Visible = false;
            this.Label2.Visible = false;
            Frame5.Enabled = false;
            Frame4.Enabled = false;
        }
        public void reset_Renamed()
        {
            //this.hider1.IsReduced = false;
            //ModMain.SYNC = false;
            //ModMain.csystate = Mcsy.csyState.enmReady ;
            CommandWeight.Enabled = true;
            if (Check1.CheckState == CheckState.Checked)
            {
                ctp1.startit();
            }
            Frame5.Enabled = true;
            Frame4.Enabled = true;
            this.Label1.Visible = true;
            this.Label2.Visible = true;
            // csy1.reset
            //isstart = false;
            CommandStop.Enabled = false;
            CommandStart.Enabled = true;
            //debug.print busy, "busy"
            //TimerJieqi.Enabled = True : jqcount = 0
            ModMain.busy = false;
        }
        private void CommandStop_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            csy1.stopCsy();
            this.reset_Renamed();
        }

        private void CommandWeight_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            CommandWeight.Enabled = false;
            double x = 0;
            ctp1.stopit();
            Check1.CheckState = System.Windows.Forms.CheckState.Unchecked;
            try
            {
                x = ctp1.READ();
                TextSampleWeight.Text = string.Format("{0:F4}", x);
            }
            catch (System.TimeoutException e)
            {
                modLog.savelogmsg("天平未准备好!");
                modLog.showLog();
                modLog.savelogmsg(e.ToString());
            }
            CommandWeight.Enabled = true;
        }

        public void dReceiveMulti(double x1, ref double[] y, int n)
        {
            int i = 0;
            mysig.setPoint(x1, mysig.xn);
            for (i = 0; i <= ModMain.NUMChanel - 1; i++)
            {
                mysig.setPoint(y[i], Convert.ToString(i), mysig.xn);
                //if (firstp)
                //{
                //    mcurve1.starttmpline(x1, y[i], i);
                //    firstp = false;
                //}
                //else
                //{
                    mcurve1.tmplineaddpoint(x1, y[i], i);
                //}
            }
            mysig.xn = mysig.xn + 1;
        }



        private void csy1_dataEnd(System.Object Sender, Mcsy.dataEndEventArgs e)
        {
            int i = e.i;
            dEnd(i);
        }

        private void csy1_dataReceiveMulti(System.Object Sender, Mcsy.dataReceiveMultiEventArgs e)
        {
            double x = e.x;
            double[] y = e.y;
            int i = e.i;
            dReceiveMulti(x, ref y, i);
        }

        private void csy1_Finish(System.Object Sender, System.EventArgs e)
        {
            //dFinish();
        }


        public void dFinish()
        {
            calcAll(true);
            record(); //save data
            this.TextSampleWeight.Text = "0.0000";
            this.Text4.Text = "0.0000";
            reset_Renamed();
            showcurRegion();
        }

        private void csy1_myErr(System.Object Sender, Mcsy.myErrEventArgs e)
        {
            int n = e.n;
            string d = e.d;
            modLog.savelogmsg(Convert.ToString(n) + ":" + d);
            modLog.showLog();
            statusError.Text = e.d;
            switch (n)
            {
                case -1:
                case -3:
                case -5:
                case -6:
                    this.reset_Renamed();
                    break;
            }
        }



        private void csy1_myLog(System.Object Sender, Mcsy.myLogEventArgs e)
        {
            int n = e.n;
            string d = e.d;
            modLog.savelogmsg(d);
        }


        private void frmMain_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
        {
            csy1.shutdown();
            jf1 = null;
            //ModMain.gDb.setLastUser(ModMain.user1.mname);
            ModMain.program1.lastUser = ModMain.user1.mname;
            ModMain.endProgram();
        }
        public void setDi()
        {
            int nvlv = 0;
            int[] vlV = null;
            vlV = null;
            string[] vlvName = null;
            vlvName = null;
            ModMain.gDb.getDiSet(ref vlV, ref vlvName, ref nvlv);
            //Call Me.csy1.setDi(vlV, vlvName, nvlv)
        }
        public void setvlv()
        {
            ModMain.vlV = null;
            ModMain.vlvName = null;
            ModMain.gDb.getvlvset(ref ModMain.vlV, ref ModMain.vlvName, ref ModMain.nvlv);
            this.csy1.setvlv();
            int nchn = 0;
            string[] chnName = null;
            nchn = 16;
            chnName = new string[nchn + 1];
            chnName[0] = "反馈电压";
            chnName[1] = "反馈电流";
            chnName[2] = "2";
            chnName[3] = "3";
            chnName[4] = "4";
            chnName[5] = "5";
            chnName[6] = "6";
            chnName[7] = "7";
            chnName[8] = "水温";
            chnName[9] = "净化炉温";
            chnName[10] = "转化炉温";
            chnName[11] = "11";
            chnName[12] = "12";
            chnName[13] = "13";
            chnName[14] = "14";
            chnName[15] = "15";
            chnName[ModMain.getEleChanel("C")] = "O";
            chnName[ModMain.getEleChanel("S")] = "N";
            chnName[ModMain.getEleChanel("C2")] = "O2";
            chnName[ModMain.getEleChanel("S2")] = "N2";

            csy1.displaychn(ref chnName, ref nchn);

            //AD0:    低硫通道(低硫调零曲线调整范围)
            //AD1:    高碳通道(高碳调零曲线调整范围)
            //AD2:    低碳通道(低碳调零曲线调整范围)
            //AD3:    高硫通道()
            //AD4:    备用()
            //AD5：流量传感器信号,
            //AD6：压力传感器信号,显示压力y=30x千帕。例如5V对应150千帕
            //AD7：高频功率参数,显示功率y=880x瓦特。例如2V对应1760瓦特
            //AD8：红外箱温度,显示温度y=(10x+4)摄氏度.例如：3.6V对应40摄氏度
            //AD9：氧化铜炉温,显示温度y=100x摄氏度.例如：3.6V对应360摄氏度
            //AD10:   红外光源电压, (y = x)
            //AD11：+5V,（y=x）
            //AD12：+10V,（y=0.5x）
            //AD13：-12V,（y=0.5x）
            //AD14：+12V,（y=0.5x）
            //AD15：+24V,（y=0.25x）

        }
        private void frmMain_Load(System.Object eventSender, System.EventArgs eventArgs)
        {
            this.csy1.initElse();
            ctp1 = new CTP();
            this.csy1.startdi();
            this.mcurve1.setxyDw("s", "V");
            printFont = new Font("Arial", 10.5F);
            ModMain.program1.isON = true;
            //if (ModMain.program1.isON)
            //{
            //    if (ModMain.program1.demo == true)
            //    {
            //        this.Text = "NCS_ONH.NET演示版";
            //    }
            //    else
            //    {
            //        this.Text = "NCS_ONH.NET";
            //    }
            Check2.Text = "低氧";
            Check3.Text = "低氮";
            Check4.Text = "高氧";
            Check5.Text = "高氮";
            Label4.Text = "O%";
            Label3.Text = "N%";

            //}
            //else
            //{
            //    if (ModMain.program1.demo == true)
            //    {
            //        //this.Text = NCS_CS.My.MyProject.Application.Info.Title + "演示版";
            //    }
            //    else
            //    {
            //        //this.Text = NCS_CS.My.MyProject.Application.Info.Title;
            //    }
            //}
            if (ModMain.method1 == null)
            {
            }
            else
            {
                csy1.setmethodpara();
            }
            setvlv();
            setDi();
            this.settp(ModMain.program1.tpid);
            ModMain.busy = true;
            SSTab1.SelectedIndex = 0;
            if (ModMain.user1.mname != "system")
            {
                SSTab1.TabPages[1].Visible = false;
            }
            csy1.link();
            //double[] x = null;
            //int n = 0;
            //, y() As Single, n As int
            //x = new double[2001];
            //n = 0;
            //mysig = new Sig();
            ModMain.gDb.delIDS();
            //mysig.xn = 0;
            //isstart = false;
            jf1 = new JF2();
            refreshSelSample();
            this.displayMethod();
            //x = new double[2];
            //object[] y = new object[2];
            //object[] sx = new object[2];
            //object[] sy = new object[2];

            //初始化界面
            if (ModMain.user1.autoweight)
            {
                Check1.CheckState = System.Windows.Forms.CheckState.Checked;
            }
            else
            {
                Check1.CheckState = System.Windows.Forms.CheckState.Unchecked;
            }
            CommandStop.Enabled = false;
            this.setLabelColor();
        }

        void setLabelColor()
        {
            Color c = ModMain.getChanelColor("C");
            //mcurve1.setlinecolor(0, c);
            this.label6.BackColor = c;
            c = ModMain.getChanelColor("S");
            //mcurve1.setlinecolor(1, c);
            this.label8.BackColor = c;
            c = ModMain.getChanelColor("C2");
            //mcurve1.setlinecolor(2, c);
            this.label10.BackColor = c;
            c = ModMain.getChanelColor("S2");
            //mcurve1.setlinecolor(3, c);
            this.label12.BackColor = c;

        }
        public void loadmethod_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            FrmLoadmethod fm = new FrmLoadmethod();
            fm.ShowDialog();
            if (fm.mconfirm)
            {
                //user1.method_Renamed = FrmLoadmethod.methodname
                ModMain.user1.methodid = fm.methodid;

                //
                ModMain.gDb.myLoadmethodByid((ModMain.user1.mname), (ModMain.user1.methodid));


                //csy1.setswitch((method1.cswitch), (method1.sswitch))
                //Call gDb.myLoadmethod(user1.mname, user1.method)
                csy1.setmethodpara();
                ModMain.gDb.saveUser(ref ModMain.user1);
                //Label3.Caption = "方法名称:" + user1.method
                //    sbStatusBar.Panels(1).Text = user1.mname + "," + user1.method
                this.displayMethod();
            }
        }

        public void mnuChanels_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                if (ModMain.checkuser())
                {
                    frmchanel fm = new frmchanel();
                    fm.ShowDialog();
                    this.refreshSelSample();
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnuChangePwd_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            frmChangePWD fm = new frmChangePWD();
            fm.ShowDialog();
            if (fm.LoginSucceeded)
            {
                //change it
                //ModMain.gDb.changePwd(ModMain.user1, fm.txtUserName.Text);
                ModMain.user1.mpassword = fm.txtUserName.Text;
                ModMain.getsession().Update(ModMain.user1);
                ModMain.getsession().Flush();
            }
            else
            {
            }
        }

        public void mnuClear_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            ModMain.busy = true;
            ModMain.gDb.delIDS();
            refreshSelSample();
            ModMain.busy = false;
        }

        public void mnuClearSelect_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            ModMain.busy = true;

            if (DataGrid1.SelectedRows.Count < 1)
            {
                MessageBox.Show("请选择单次数据", "");
                return;
            }
            foreach (System.Windows.Forms.DataGridViewRow b in DataGrid1.SelectedRows)
            {

                ModMain.gDb.delidsOne((int)b.Cells["sampleid"].Value);
            }
            refreshSelSample();
            ModMain.busy = false;
        }

        public void mnuCloseGPPower_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            csy1.closeGp();
        }

        public void mnuContent_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //Shell("start " + initpath + "\ncscs1.hlp")
            //ShellExecute(0, "open", initpath + "\CS-2008操作手册.mht", "", "", AppWinStyle.NormalFocus)
            System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
            ps.UseShellExecute = true;
            ps.Verb = "open";
            ps.FileName=modLog.initpath + "\\NCS_ONH.NET软件操作手册.mht";
            System.Diagnostics.Process.Start(ps); 
            //System.AppDomain.ExecuteAssembly("start '" + initpath + "\CS-2008操作手册.mht'")
            //Application. 
        }

        public void mnuContrast_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            ModMain.busy = true;
            int i = 0;
            Sig[] sigs = null;
            System.Collections.ArrayList sid;
            sid = new System.Collections.ArrayList();
            frmSelectChanel fm;
            if (DataGrid1.SelectedRows.Count > 0)
            {
                fm = new frmSelectChanel();
                fm.ShowDialog();
                if (!fm.confirm)
                    return;
            }
            else
            {
                MessageBox.Show("请选择单次数据", "");
                return;
            }
            int chanel_Renamed = 0;
            chanel_Renamed = fm.the;
            int id = 0;
            foreach (System.Windows.Forms.DataGridViewRow b in DataGrid1.SelectedRows)
            {
                id = (int)b.Cells["id"].Value;
                sid.Add(id);
            }
            sigs = new Sig[sid.Count];
            foreach (int c in sid)
            {
                sigs[i] = new Sig();
                ModMain.loadsignew(ref sigs[i], c);
                i++;
            }
            mcurve1.clear();
            mcurve1.setLineCount(Convert.ToInt16(sid.Count));
            try
            {
                for (i = 0; i < sid.Count; i++)
                {
                    sigs[i].mcurveSetarrv(ref mcurve1, chanel_Renamed, i);
                }
                mcurve1.fit();
            }
            catch (System.NullReferenceException e)
            {
                modLog.savelogmsg(e.ToString());
            }
            ModMain.busy = false;
        }

        public void mnucopy_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //Dim sid() As int
            //Dim c As int
            ModMain.busy = true;
            string s = null;
            s = "";
            if (DataGrid1.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择单次数据", "");
                return;
            }
            //object b = null;
            s = s + "method\0x9";// + char(9);
            s = s + "date\0x9"; //+ char(9);
            s = s + "cname\0x9"; //+ char(9);
            s = s + "id\0x9";//+ Strings.Chr(9);
            s = s + "O_area\0x9";// + Strings.Chr(9);
            s = s + "O\0x9";//+ Strings.Chr(9);
            s = s + "N_area\0x9";// + Strings.Chr(9);
            s = s + "N\r\n"; //+ "\r\n";
            //With gdb.rsselSample
            //foreach (object b_loopVariable in DataGrid1.SelectedRows) {
            //    b = b_loopVariable;
            //    //UPGRADE_WARNING: Couldn't resolve default property of object b. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
            //    //.Bookmark = b
            //    //addDynaArrDistinct sid, .Fields("sampleid").value
            //    s = s + (b.Cells["method"].Value) + Strings.Chr(9);
            //    s = s + Convert.ToString(b.cells("mdate").Value) + Strings.Chr(9);
            //    s = s + (b.cells("name").Value) + Strings.Chr(9);
            //    s = s + Convert.ToString(b.Cells["id"].Value) + Strings.Chr(9);
            //    s = s + Convert.ToString(b.Cells["carea"].Value) + Strings.Chr(9);
            //    s = s + string.Format("{0:F5}", b.Cells["c"].Value) + Strings.Chr(9);
            //    s = s + Convert.ToString(b.Cells["sarea"].Value) + Strings.Chr(9);
            //    s = s + string.Format("{0:F5}", b.Cells["s"].Value) + "\r\n";
            //    //    c = c + 1
            //}
            //End With
            //NCS_CS.My.MyProject.Computer.Clipboard.Clear();
            //NCS_CS.My.MyProject.Computer.Clipboard.SetText(s);
            ModMain.busy = false;
        }

        public void mnucopyAll_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            this.DataGrid1.SelectAll();
        }

        public void mnuCuanCur_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //string s = null;
            //if (this.DataGrid2.CurrentRow == null) {

            //} else {
            //    {
            //        s = "{";
            //        s = s + "name:" + this.DataGrid2.CurrentRow.Cells("name").Value + ",";
            //        s = s + "C:" + Convert.ToString(this.DataGrid2.CurrentRow.Cells["c"].Value) + ",";
            //        s = s + "S:" + Convert.ToString(this.DataGrid2.CurrentRow.Cells["s"].Value) + ",";
            //        s = s + "date:" + Convert.ToString(this.DataGrid2.CurrentRow.Cells("mdate").Value);
            //        s = s + "}";
            //    }
            //    Clipboard.SetText(s);
            //    ModMain.m_python.Globals("current") = this.DataGrid2.CurrentRow;
            //    RunScript("CuanCurrent.py");
            //}
        }

        public void mnuCuanSelect_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //ModMain.busy = true;
            //object b = null;
            //if (DataGrid2.SelectedRows.Count < 1) {
            //    MessageBox.Show("请选择平均数据");
            //    return;
            //}
            //string s1 = null;
            //string s = null;
            //s1 = "";
            ////With gdb.rsselAVe
            //foreach (object b_loopVariable in DataGrid2.SelectedRows) {
            //    b = b_loopVariable;
            //    //UPGRADE_WARNING: Couldn't resolve default property of object b. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
            //    {
            //        s = "{";
            //        s = s + "name:" + b.cells("name") + ",";
            //        s = s + "C:" + b.Cells["c"] + ",";
            //        s = s + "S:" + b.Cells["s"] + ",";
            //        s = s + "date:" + b.cells("mdate");
            //        s = s + "}";
            //        s1 = s1 + s;
            //    }
            //}
            ////End With
            ////upload1.CuanStr(s1) '一次传输
            //ModMain.busy = false;
        }

        public void mnueditWeight_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            frmWeight fm = new frmWeight();
            fm.Show();
        }

        public void mnuExit_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //if (!ModMain.makemethod) {
            this.Close();
            //    System.Environment.Exit(0);
            ////} else {
            ////    //UPGRADE_NOTE: Object rec1 may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
            ////    ModMain.getFrmMethod().FromMainReturn();
            ////    this.Visible = false;
            ////}
        }

        public void mnuExport_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                if (mysig.xn < 1)
                {
                    modLog.savelogmsg("当前无数据!");
                    modLog.showLog();
                    return;
                }
                CommonDialog1Save.DefaultExt = ".txt";
                if (!string.IsNullOrEmpty(sample1.name))
                {
                    CommonDialog1Save.FileName = sample1.name + ".txt";
                }
                if (CommonDialog1Save.ShowDialog() != DialogResult.OK)
                { return;}
                System.IO.FileStream f1 = new FileStream(CommonDialog1Save.FileName, FileMode.Create, FileAccess.Write);
                System.IO.StreamWriter f = new StreamWriter(f1);
                f.Write(sample1.name);
                f.Write("\r\n");
                f.Write(sample1.weight.ToString());
                f.Write("\r\n");
                int i = 0;
                for (i = 0; i <= mysig.xn - 1; i++)
                {
                    mysig.myprintline(f, i);
                }
                f.Close();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnuFurnace_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            csy1.reverseFurnace();
        }

        public void mnugl_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                if (ModMain.checkuser())
                {
                    frmUser fm = new frmUser();
                    fm.ShowDialog();
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnuHelpAbout_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            frmAbout f=new frmAbout();f.ShowDialog();
            //MsgBox "版本 " + App.Major + "." + App.Minor + "." + App.Revision
        }


        private void mnuHelpContents_Click()
        {
            //    Dim nRet As int
            //
            //
            //    '如果这个工程没有帮助文件，显示消息给用户
            //    '可以在“工程属性”对话框中为应用程序设置帮助文件
            //    If Len(App.HelpFile) = 0 Then
            //        MsgBox "无法显示帮助目录，该工程没有相关联的帮助。", vbInformation, Me.Caption
            //    Else
            //        On Error Resume Next
            //        nRet = OSWinHelp(Me.hwnd, App.HelpFile, 3, 0)
            //        If Err Then
            //            MsgBox Err.Description
            //        End If
            //    End If

        }



        public double getC()
        {
            return sample1.c;
        }
        public double getCarea()
        {
            return sample1.cArea;
        }
        public double getWeight()
        {
            return sample1.weight;
        }

        public void calc()
        {
            try
            {
                calcAll(true);
                this.showcurSig();
                return;
            }
            catch (System.Exception e)
            {
                log.Info(e.ToString());
            }
        }
        public void record()
        {
            modLog.savelogmsg("record");
            int sid = 0;
            int sampleid = 0;
            sampleid = ModMain.nextSampleId();
            if (sampleid == -1)
                return;
            ModMain.gDb.insertIdsOne(sampleid);
            ISession s = ModMain.getsession();
            ITransaction t = s.BeginTransaction();
            try
            {
                sample1.user = ModMain.user1.mname;
                sample1.mdate = System.DateTime.Now;
                sample1.method = ModMain.method1.cname;
                sample1.sampleid = sampleid;
                sample1.anaxuhao = 1;
                s.Save(sample1);
                s.Flush();
                s.Refresh(sample1);
                sid = sample1.ID;
                t.Commit();
            }
            catch (System.Exception e)
            {
                t.Rollback();
                log.Info(e.ToString());
            }
            finally {
                s.Close();
                s.Dispose();
            }
            mysig.save(sid);
            this.refreshSelSample();
        }



        public void mnuImport_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {

                CommonDialog1Open.DefaultExt = ".txt";

                CommonDialog1Open.FileName = "";

                CommonDialog1Open.ShowDialog();

                if (!string.IsNullOrEmpty(CommonDialog1Open.FileName))
                {
                    ImportStartOne(CommonDialog1Open.FileName);
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnuLink_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            csy1.link();
        }

        public void mnuOpenGp_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //csy1.OpenGp()
        }

        public void mnuPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //btnPrintPreview_Click(this.DataGrid2);
            //FormPrintRtf fm = new FormPrintRtf();
            //fm.ShowDialog(); 
            //FormHtmlEditorMethod fm = new FormHtmlEditorMethod();
            //fm.ShowDialog(); 
            System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(NCS.method));
            System.IO.StreamWriter stream = new System.IO.StreamWriter("method.xml");
            s.Serialize(stream, ModMain.method1);

        }


        public void mnuPrintAll_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //btnPrintPreview_Click(this.DataGrid1);
            //FormRtfC  fm = new FormRtfC();
            //fm.ShowDialog(); 
        }

        public void mnuPrintSingleAndAver_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            FormRDlPrint f = new FormRDlPrint();
            f.ShowDialog();
            //
            //Call printSingleAndAverage()
            //FormPrint fp = new FormPrint();
            //fp.ShowDialog();
            //fyiReporting.RdlDesign.RdlDesigner d = new fyiReporting.RdlDesign.RdlDesigner();
            //d.openFile(modLog.initpath + "\\ListReport.rdl");//, null, false);
            //d.ShowDialog(); 
        }



        public void qcali()
        {
            frmChanels fm = new frmChanels();
            //if (null == ModMain.getFrmMethod())
            //{ ModMain.getFrmMethod() = new FrmMethod(); }
            fm.ShowDialog();
            if (fm.conform)
            {
                //FrmMethod.
                if (fm.Check2.CheckState == CheckState.Checked)
                {
                    ModMain.getFrmMethod().caliChanel("C");
                    //NCS_CS.My.Forms.
                }
                if (fm.Check3.CheckState == CheckState.Checked)
                {
                    ModMain.getFrmMethod().caliChanel("S");
                }
                if (fm.Check4.CheckState == CheckState.Checked)
                {
                    ModMain.getFrmMethod().caliChanel("C2");
                }
                if (fm.Check5.CheckState == CheckState.Checked)
                {
                    ModMain.getFrmMethod().caliChanel("S2");
                }
                this.Hide();
                ModMain.getFrmMethod().Show();

            }
        }
        public void mnuQuickMethod_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            qcali();
            //FrmMethod.Show vbModal
        }

        public void mnuRecalc_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //try
            //busy = True
            //With gdb.rsselSample
            //  If .RecordCount > 0 And Not .BOF And Not .EOF Then
            //    calcId .Fields("id").value
            //    .Fields("c").value = sample1.c
            //    .Fields("s").value = sample1.s
            //    .Fields("ishc").value = sample1.ishc
            //    .Fields("ishs").value = sample1.ishs
            //    .Fields("carea").value = sample1.cArea
            //    .Fields("sarea").value = sample1.sArea
            //    .Fields("cindex").value = sample1.cindex
            //    .Fields("cindex2").value = sample1.cindex2
            //    .Fields("sindex").value = sample1.sIndex
            //    .Fields("sindex2").value = sample1.sIndex2
            //    .Update
            //    Me.delAveOne .Fields("sampleid").value
            //    Me.addAVeOne .Fields("sampleid").value
            //    Me.insertOneid .Fields("sampleid").value
            //    Me.refreshSelAve
            //  End If
            //End With
            //busy = False
            //Exit Sub
            //Catch e As System.Exception
            //  saveerrmsg
        }

        public void mnuRecalcSelect_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            if (DataGrid1.SelectedRows.Count > 0)
            {
            }
            else
            {
                MessageBox.Show("请选择单次数据", "");
                return;
            }
            System.Collections.ArrayList sid;
            sid = new System.Collections.ArrayList();
            int ID = 0;
            ISession session = ModMain.getsession();
            System.DateTime t1 = System.DateTime.Now;
            foreach (System.Windows.Forms.DataGridViewRow b in DataGrid1.SelectedRows)
            {
                ID = (int)b.Cells["id"].Value;
                calcId(ID);
                sid.Add((int)b.Cells["sampleid"].Value);
                session.Update(sample1);
            }
            
            session.Flush();
            System.DateTime t2 = System.DateTime.Now;
            System.TimeSpan cha = t2 - t1;
            Debug.Print(cha.ToString());
            foreach (int c in sid)
            {
                //ModMain.gDb.delaveOne(c);
                //ModMain.gDb.insertAveOne(c);
                //NCS.SampleAve ave = (NCS.SampleAve)session.Get(typeof(NCS.SampleAve), c);
                //session.Refresh(ave);
                insertOneid(c);
            }
            System.DateTime t3 = System.DateTime.Now;
            cha = t3 - t2;
            Debug.Print(cha.ToString());
            this.refreshSelSample();
        }

        public void mnuReset_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            csy1.reset_Renamed();
        }

        public void mnusaveweight_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //saveweight = Not saveweight
            //mnusaveweight.Checked = saveweight
        }

        public void mnuSet_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //frmOptions.ShowDialog()
            //If frmOptions.isCancel Then Exit Sub
            //If DEMO Then

            //    'ElseIf demoSam Then

            //Else
            //    '   csy1.reset
            //End If
        }

        public void mnuSetCuanSh_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            RunScript("CuanSet.py");
        }

        public void mnuSetStandard_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
        }
        public void datagrid1Save()
        {
            //    DataTable tsrc = null;
            //    tsrc = (System.Data.DataTable )DataGrid1.DataSource;
            //    DataTable t = null;
            //    //DataGrid1.EndEdit()
            //    t = tsrc.GetChanges();
            //    if (t == null)
            //        return;
            //    int i = 0;
            //    int n = 0;
            //    n = t.Rows.Count;
            //    int id = 0;
            //    //, name As String
            //    int sid = 0;
            //    System.Data.OleDb.OleDbCommand cmd1 = null;
            //    System.Data.OleDb.OleDbConnection con = null;
            //    con = ModMain.getCon();
            //    for (i = 0; i <= n - 1; i++) {
            //        switch (t.Rows[i].RowState) {
            //            case DataRowState.Added:
            //                break;
            //            //id = t.Rows[i].Item("id")
            //            //cmd1 = con.CreateCommand()
            //            //cmd1.CommandText = "insert into  sample() values()"
            //            //cmd1.Parameters.AddWithValue("vid", id)
            //            //cmd1.ExecuteNonQuery()
            //            case DataRowState.Modified:
            //                if (object.ReferenceEquals(t.Rows[i].Item("standardid").GetType(), typeof(System.DBNull))) {
            //                    sid = 0;
            //                } else {
            //                    sid = t.Rows[i].Item("standardid");
            //                }

            //                id = t.Rows[i].Item("id");

            //                if (object.ReferenceEquals(t.Rows[i].Item("cname").GetType(), typeof(System.DBNull))) {
            //                    Name = "";
            //                } else {
            //                    Name = t.Rows[i].Item("cname");
            //                }
            //                cmd1 = con.CreateCommand();
            //                cmd1.CommandText = "update sample set cname=@vname,standardid=@vsid where id=@vid";
            //                cmd1.Parameters.AddWithValue("vname", Name);
            //                cmd1.Parameters.AddWithValue("vsid", sid);
            //                cmd1.Parameters.AddWithValue("vid", id);
            //                cmd1.ExecuteNonQuery();
            //                break;
            //            case DataRowState.Deleted:
            //                id = t.Rows[i].Item("id");
            //                cmd1 = con.CreateCommand();
            //                cmd1.CommandText = "delete sample  where id=@vid";
            //                cmd1.Parameters.AddWithValue("vid", id);
            //                cmd1.ExecuteNonQuery();
            //                break;
            //        }
            //    }
            //    con.Close();
            //    con.Dispose();
            //    tsrc.AcceptChanges();
        }
        public void mnuSetStandardSelect_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            string mname = null;
            int stid = 0;
            int id = 0;
            //Dim s As NCS.sample
            FrmStandard fm=new FrmStandard() ;
            try
            {
                fm.ShowDialog();
                System.Windows.Forms.DataGridViewRow cr = null;
                NCS.sample s = null;
                if (fm.mconfirm)
                {
                    cr = fm.DataGrid1.CurrentRow;
                    mname = (string)cr.Cells["name"].Value;
                    stid = (int)cr.Cells["id"].Value;
                    foreach (DataGridViewRow cr2 in this.DataGrid1.SelectedRows)
                    {
                        id = (int)cr2.Cells["id"].Value;
                        s = (NCS.sample)ModMain.getsession().Get(typeof(NCS.sample), id);
                        s.name = mname;
                        s.standardid = stid;
                        ModMain.getsession().Save(s);
                    }
                    ModMain.getsession().Flush();
                    this.refreshSelSample();
                    fm.mconfirm = false;
                }
            }
            catch (Exception e1)
            {
                modLog.savelogmsg(e1.ToString());
            }
        }

        public void mnuSettpmodel_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            frmSetTp fm = new frmSetTp();
            fm.ShowDialog();
        }

        public void mnuShow_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            modLog.showLog();
        }
        private void dEnd(int i)
        {
            mysig.setstoped(i, true);
            modLog.savelogmsg("stoped" + Convert.ToString(i) + " " + Convert.ToString(mysig.getstoped(i)));
            //cCheck1.dEnd[i]
        }

        private void msample1_dataEnd(ref int i)
        {
            mysig.setstoped(i, true);
        }

        private void Msample1_dataReceive(ref double x, ref double y, ref int i)
        {
            // dReceive x, y, i
        }

        private void msample1_dataReceiveMulti(ref double x, ref double[] y, ref int i)
        {
            dReceiveMulti(x, ref y, i);
        }

        private void Msample1_Finish()
        {
            dFinish();
        }

        private void Msample1_myErr(ref int num, ref string des)
        {
            modLog.savelogmsg(Convert.ToString(num) + des);
        }

        public void mnuShualu_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //csy1.reverseShua()
        }

        public void mnuTestBaseline_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //ModMain.SYNC = true;
            //ModMain.csystate = Mcsy.csyState.enmSync;
            if (csy1.changeCsyState(Mcsy.csyState.enmSync))
            {
                CommandStart_Click(CommandStart, new System.EventArgs());
            }
        }

        public void mnuTiaoLing_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            frmTiaoling fm=new frmTiaoling();
            fm.ShowDialog();
        }

        public void mnuTiaoshi_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                if (ModMain.checkuser())
                {
                    SSTab1.TabPages[1].Visible = true;
                    //UPGRADE_ISSUE: TabDlg.SSTab property SSTab1.TabsPerRow was not upgraded. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
                    //SSTab1.TabsPerRow = 2
                    SSTab1.SelectedIndex = 1;
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnutiaoZhengJX_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            double t = 0;
            //if csy1.
            csy1.tiaozhengBase(t);
        }



        private void SSTab1_SelectedIndexChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            //Static PreviousTab As int = SSTab1.SelectedIndex()
            //If PreviousTab = 0 Then
            //    '    csy1.debugMode = True
            //    Frame7.Visible = False
            //    Frame6.Visible = True
            //Else
            //    Frame6.Visible = False
            //    Frame7.Visible = True
            //End If
            //PreviousTab = SSTab1.SelectedIndex()
        }

        private void TextSampleWeight_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            System.Windows.Forms.SendKeys.Send("{Home}+{End}");
        }
        public void opensample()
        {
            FrmOpenSample f = new FrmOpenSample();
            f.ShowDialog();
            int i = 0;
            int n = 0;
            n = f.DataGrid1.Rows.Count;
            System.Windows.Forms.DataGridViewRow r = null;
            int sid = 0;
            System.DateTime t1 = System.DateTime.Now;
            ArrayList ids = new ArrayList();
            for (i = 0; i <= n - 1; i++)
            {
                if (f.DataGrid1.Rows[i].Selected == true)
                {
                    r = f.DataGrid1.Rows[i];
                    if (null != r.Cells["sampleid"].Value)
                    {
                        sid = (int)r.Cells["sampleid"].Value;
                        ids.Add(sid);
                    }
                }
            }
            ModMain.gDb.insertIds(ids);
            System.DateTime t2 = System.DateTime.Now;
            System.TimeSpan cha = t2 - t1;
            Debug.Print(cha.ToString());
            refreshSelSample();
            System.DateTime t3 = System.DateTime.Now;
            cha = t3 - t2;
            Debug.Print(cha.ToString());
        }



        private void TimerJieqi_Tick(System.Object eventSender, System.EventArgs eventArgs)
        {
            //jqcount = jqcount + 1;
            //if (jqcount > 5 * 60)
            //{
            //    csy1.jieqi();
            //    jqcount = 0;
            //}
        }

        private void Toolbar1_ButtonClick(System.Object eventSender, System.EventArgs eventArgs)
        {
            System.Windows.Forms.ToolStripItem Button = (System.Windows.Forms.ToolStripItem)eventSender;
            ModMain.busy = true;
            //switch (Button.Name) {
            //    case "_Toolbar1_Button1":
            //        //"method"
            //        //  loadmethod_Click
            //        changeMethod_Click(changeMethod, new System.EventArgs());
            //        break;
            //    case "_Toolbar1_Button2":
            //        //"base"
            //        mnuTestBaseline_Click(mnuTestBaseline, new System.EventArgs());
            //        break;
            //    //Case "_Toolbar1_Button3" '"link"
            //    //    csy1.link()
            //    case "_Toolbar1_Button3":
            //        //"open"
            ModMain.getFrmResult().Hide();
            opensample();
            //        break;
            //    case "_Toolbar1_Button4":
            //        //"start"
            //        delrec();
            //        break;
            //    case "_Toolbar1_Button5":
            //        //"stop"
            //        avgrec();
            //        break;
            //    case "_Toolbar1_Button6":
            //        //"reset"
            //        csy1.jiayang();
            //        break;
            //    case "_Toolbar1_Button7":
            //        //"furnace"
            //        csy1.reverseFurnace();
            //        break;
            //    case "_Toolbar1_Button8":
            //        //"clear"
            //        mnuClear_Click(mnuClear, new System.EventArgs());
            //        break;
            //}
            //ModMain.busy = false;
            //showcurOne
        }
        public void loadSample(int sid)
        {
            //try
            //{
                sample1 = (NCS.sample)ModMain.getsession().Get(typeof(NCS.sample), sid);
                return;
            //}
            //catch (System.Exception e)
            //{
            //    modLog.savelogmsg(e.ToString());
            //}
        }


        public void loadStartOne(int sid)
        {
            try
            {
                setRun();
                if (ModMain.method1 == null)
                    return;
                loadSample(sid);
                //  TextSampleWeight.Text = sample1.weight
                int i = 0;
                for (i = 0; i <= ModMain.NUMChanel - 1; i++)
                {
                    mysig.setstoped(i, false);
                }
                mysig.xn = 0;
                mcurve1.setLineCount(4);
                mcurve1.init();
                this.setlineColor();
                //isstart = true;
                firstp = true;
                //firsts = true;
                ModMain.loadsignew(ref mysig, sid);
                //   'debug.print mysig.xn, mysig.yn(0), mysig.yn(1)
                dFinish();
                reset_Renamed();
                return;
            }
            catch (System.Exception e)
            {
                reset_Renamed();
                modLog.savelogmsg(e.ToString());
            }
        }

        //public void loadStart()
        //{
        //    loadStartOne( My.MyProject.Forms.FrmOpenSample.sid);
        //}
        //public void loadOnly()
        //{
        //    loadOnlyOne(My.MyProject.Forms.FrmOpenSample.sid,  My.MyProject.Forms.FrmOpenSample.sampleid);
        //}
        public void loadOnlyOne(int sid, int sampleid)
        {
            try
            {
                setRun();
                loadSample(sid);
                insertOneid(sampleid);
                refreshSelSample();
                reset_Renamed();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
                reset_Renamed();
            }
        }

        public void insertOneid(int sid)
        {
            try
            {
                ModMain.gDb.insertIdsOne(sid);
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void xishuformat(object sender, System.Windows.Forms.ConvertEventArgs e)
        {
            //e.Value = e.Value.ToString("F7", CultureInfo.InvariantCulture)
            e.Value = string.Format("{0:F5}", e.Value);
        }
        public void refreshSelSample()
        {

            IList o = null;
            o = ModMain.getsession().CreateSQLQuery(SAMPLESTR).AddEntity(typeof(NCS.sample)).List();

            samples = new SortableBindingList2<NCS.sample>();
            System.ComponentModel.Container Mecomponents = new System.ComponentModel.Container();
            System.Windows.Forms.BindingSource MeMuserBindingSource = new System.Windows.Forms.BindingSource(Mecomponents);
            foreach (NCS.sample one in o)
            {
                //MeMuserBindingSource.Add(one);
                samples.Add(one);
            }
            MeMuserBindingSource.DataSource = samples;//typeof(NCS.sample);
            //DataGrid1.DataSource = Nothing

            DataGrid1.DataSource = MeMuserBindingSource;// samples;
            MeMuserBindingSource.MoveLast();
            DataGrid1.AllowUserToAddRows = false;
            //If o.Count < 1 Then
            //    Exit Sub
            //End If
            this.Label1.Text = "";
            this.Label2.Text = "";
            if (ModMain.getChanelEnable("C") == false & ModMain.getChanelEnable("C2") == false)
            {
                Label1.DataBindings.Clear();
            }
            else
            {
                //Call rebind(Me.Label2, "Text", o, "c")
                Label1.DataBindings.Clear();
                System.Windows.Forms.Binding b = new System.Windows.Forms.Binding("Text", samples, "c");
                b.Format += xishuformat;
                Label1.DataBindings.Add(b);
            }
            if (ModMain.getChanelEnable("S") == false & ModMain.getChanelEnable("S2") == false)
            {
                Label2.DataBindings.Clear();
            }
            else
            {
                //Call rebind(Me.Label1, "Text", o, "s")
                Label2.DataBindings.Clear();
                System.Windows.Forms.Binding b = new System.Windows.Forms.Binding("Text", samples, "s");
                b.Format += xishuformat;
                Label2.DataBindings.Add(b);
            }
            {
                DataGrid1.ColumnHeadersDefaultCellStyle.Font = printFont;
            }
            foreach (DataGridViewColumn c in DataGrid1.Columns)
            {
                c.DefaultCellStyle.Font = printFont;
            }

            try
            {
                DataGrid1.AllowUserToOrderColumns = true;
                DataGrid1.Columns["mdate"].HeaderText = "分析时间";
                DataGrid1.Columns["mdate"].Width = 160;
                DataGrid1.Columns["name"].HeaderText = "样品名称";
                DataGrid1.Columns["c"].DefaultCellStyle.Format = "0.00000";
                DataGrid1.Columns["c"].HeaderText = "O%";
                DataGrid1.Columns["anaxuhao"].HeaderText = "序号";
                DataGrid1.Columns["s"].DefaultCellStyle.Format = "0.00000";
                DataGrid1.Columns["s"].HeaderText = "N%";
                DataGrid1.Columns["carea"].DefaultCellStyle.Format = "0.00";
                DataGrid1.Columns["cArea"].HeaderText = "O面积";
                DataGrid1.Columns["sarea"].DefaultCellStyle.Format = "0.00";
                DataGrid1.Columns["sArea"].HeaderText = "N面积";
                DataGrid1.Columns["weight"].DefaultCellStyle.Format = "0.0000g";
                DataGrid1.Columns["weight"].HeaderText = "质量";
                DataGrid1.Columns["wlweight"].HeaderText = "助熔剂质量";
                DataGrid1.Columns["wlweight"].DefaultCellStyle.Format = "0.0000g";
                DataGrid1.Columns["wlweight"].Width = 120;
                DataGrid1.Columns["sampleid"].HeaderText = "样品编号";
                DataGrid1.Columns["standardid"].HeaderText = "标样编号";
                DataGrid1.Columns["ishc"].HeaderText = "isho";
                DataGrid1.Columns["ishs"].HeaderText = "ishn";
                DataGrid1.Columns["sIndex"].Visible = false;
                DataGrid1.Columns["sIndex2"].Visible = false;
                DataGrid1.Columns["cIndex"].Visible = false;
                DataGrid1.Columns["cIndex2"].Visible = false;
                DataGrid1.Columns["sInt"].Visible = false;
                DataGrid1.Columns["sessionid"].Visible = false;
                DataGrid1.Columns["cInt"].Visible = false;
                DataGrid1.Columns["isHc"].Visible = false;
                DataGrid1.Columns["isHs"].Visible = false;
                DataGrid1.Columns["method"].Visible = false;
                DataGrid1.Columns["methodid"].Visible = false;
                DataGrid1.Columns["user"].Visible = false;
                if (ModMain.getChanelEnable("C") == false & ModMain.getChanelEnable("C2") == false)
                {
                    DataGrid1.Columns["c"].Visible = false;
                    DataGrid1.Columns["cArea"].Visible = false;
                }
                else
                {
                    DataGrid1.Columns["c"].Visible = true;
                    DataGrid1.Columns["carea"].Visible = true;
                }
                if (ModMain.getChanelEnable("S") == false & ModMain.getChanelEnable("S2") == false)
                {
                    DataGrid1.Columns["s"].Visible = false;
                    DataGrid1.Columns["sArea"].Visible = false;
                }
                else
                {
                    DataGrid1.Columns["s"].Visible = true;
                    DataGrid1.Columns["sarea"].Visible = true;
                }
                int sid = 0;
                DataGridViewRow r =DataGrid1.CurrentRow;
                if (r != null)
                {
                    sid = (int)r.Cells["sampleid"].Value;
                    refreshSelAveOld(sid);
                }
            }
            catch (System.NullReferenceException e1)
            {
                modLog.savelogmsg(e1.ToString());
            }




        }

        public void refreshSelAveOld(int sid)
        {
            ArrayList o=new ArrayList();
            ISession session = ModMain.getsession();
            //ICriteria criteria = session.CreateCriteria(typeof(NCS.sample));
            //criteria.SetProjection(Projections.GroupProperty("sampleid"));
            //criteria.Add(Expression.Eq("sampleid", sid));
            //criteria.SetProjection(Projections.Min("cname"));
            //criteria.SetProjection(Projections.Avg("c"));
            //criteria.SetProjection(Projections.Avg("s"));
            //criteria.SetProjection(Projections.Count("id"));
            //IList l=criteria.List();
            //string cmd = "SELECT avg(c),stdev(c), avg(s),stdev(s), max(mdate), count(id),max(cname) FROM sample WHERE sampleid="+sid.ToString()+" GROUP BY sampleid";
            //string cmd = "select avg(smp.c),avg(smp.s),count(smp) from NCS.sample smp where smp.sampleid=" + sid.ToString() + " group by smp.sampleid";
            //IList l=session.CreateQuery(cmd).List();
            //if (l.Count > 0)
            //{
            //    foreach (Object o1 in l)
            //    {
            //    SampleAve ave = new SampleAve();
            //    Object[] o11=(Object[])o1;
            //    ave.c = (double)o11[0];
            //    ave.s =(double) o11[1];
            //    ave.num = (long)o11[2];
            //    o.Add(ave);
            //    }
            //}
            IDbCommand cmd = null;
            cmd = ModMain.getsession().Connection.CreateCommand();
            cmd.CommandText = "SELECT avg(c),stdev(c), avg(s),stdev(s), max(mdate), count(id),max(cname) FROM sample WHERE sampleid="+sid.ToString()+" GROUP BY sampleid";
            IDataReader r=cmd.ExecuteReader();
            while (r.Read())
            {
                    SampleAve ave = new SampleAve();
                    Object[] o11=new Object[7];
                    int n= r.GetValues(o11);
                    ave.c = (double)o11[0];
                if(o11[1].GetType()==typeof(System.DBNull))
                {
                    //ave.cstd = (double)o11[1];
                }
                else
                {
                    ave.cstd = (double)o11[1];
                }
                    ave.s = (double)o11[2];
                    if (o11[3].GetType() == typeof(System.DBNull))
                    {
                        //ave.cstd = (double)o11[1];
                    }
                    else
                    {
                        ave.sstd = (double)o11[3];
                    }
                    ave.mdate  = (DateTime)o11[4];
                    ave.num = (int)o11[5];
                    //ave.name = (string)o11[6];
                    //if (ave.c != 0) { ave.crsd = ave.c / ave.cstd; }
                    //if (ave.s != 0) { ave.srsd =ave.s/ave.sstd; }
                    o.Add(ave);
            }
            DataGrid2.DataSource = null;
            DataGrid2.DataSource = o;
            DataGrid2.AllowUserToAddRows = false;
            if (o.Count < 1)
                return;
            //try
            //{
                DataGrid2.Columns["sessionid"].Visible = false;
                DataGrid2.Columns["methodid"].Visible = false;
                DataGrid2.Columns["user"].Visible = false;
                DataGrid2.Columns["mdate"].HeaderText = "分析时间";
                DataGrid2.Columns["mdate"].Visible = false;
                DataGrid2.Columns["name"].HeaderText = "样品名称";
                DataGrid2.Columns["name"].Visible = false;
                DataGrid2.Columns["num"].HeaderText = "个数";
                DataGrid2.Columns["sampleid"].HeaderText = "样品编号";
                DataGrid2.Columns["sampleid"].Visible = false;
                DataGrid2.Columns["c"].HeaderText = "O%";
                DataGrid2.Columns["c"].DefaultCellStyle.Format = "0.00000";
                //DataGrid2.Columns[""].HeaderText = "序号"
                //DataGrid1.Columns["s").NumberFormat = "0.00000"
                DataGrid2.Columns["s"].HeaderText = "N%";
                DataGrid2.Columns["s"].DefaultCellStyle.Format = "0.00000";
                DataGrid2.Columns["cstd"].HeaderText = "O%_SD";
                //DataGrid2.Columns["cstd"].Visible = false;
                DataGrid2.Columns["cstd"].DefaultCellStyle.Format = "0.00000";
                DataGrid2.Columns["sstd"].HeaderText = "N%_SD";
                //DataGrid2.Columns["sstd"].Visible = false;
                DataGrid2.Columns["sstd"].DefaultCellStyle.Format = "0.00000";
                DataGrid2.Columns["crsd"].HeaderText = "O%_RSD";
                //DataGrid2.Columns["crsd"].Visible = false;
                DataGrid2.Columns["crsd"].DefaultCellStyle.Format = "0.0";
                DataGrid2.Columns["srsd"].HeaderText = "N%_RSD";
                //DataGrid2.Columns["srsd"].Visible = false;
                DataGrid2.Columns["srsd"].DefaultCellStyle.Format = "0.0";
                //if (ModMain.getChanelEnable("C") == false & ModMain.getChanelEnable("C2") == false) {
                //    DataGrid2.Columns["c").Visible = false;
                //    DataGrid2.Columns["cstd").Visible = false;
                //    DataGrid2.Columns["crsd").Visible = false;
                //} else {
                //    DataGrid2.Columns["c").Visible = true;
                //    DataGrid2.Columns["cstd").Visible = true;
                //    DataGrid2.Columns["crsd").Visible = true;
                //}
                //if (ModMain.getChanelEnable("S") == false & ModMain.getChanelEnable("S2") == false) {
                //    DataGrid2.Columns["s").Visible = false;
                //    DataGrid2.Columns["sstd").Visible = false;
                //    DataGrid2.Columns["srsd").Visible = false;
                //} else {
                //    DataGrid2.Columns["s").Visible = true;
                //    DataGrid2.Columns["sstd").Visible = true;
                //    DataGrid2.Columns["srsd").Visible = true;
                //}

            //}
            //catch (System.NullReferenceException ex)
            //{
            //    modLog.savelogmsg(ex.ToString());
            //}
            return;
        }

        public void ImportStartOne(string fname)
        {
                setRun();
                sample1 = new NCS.sample();
                mysig = new Sig();
                int i = 0;
                for (i = 0; i <= ModMain.NUMChanel - 1; i++)
                {
                    mysig.setstoped(i, false);
                }
                mysig.xn = 0;
                mcurve1.setLineCount(ModMain.NUMChanel);
                mcurve1.init();
                this.setlineColor();
                //isstart = true;
                firstp = true;
                //firsts = true;
                string n = null;
                double w = 0;
                n = "";
                if (ModMain.LoadSigfromfile(ref fname, ref mysig, ref n, ref w))
                {
                    sample1.name = n;
                    sample1.weight = w;
                    showcurSigonly();
                    dFinish();
                    reset_Renamed();
                }
        }


        public void showcurveOne(int sid)
        {
            try
            {
                loadSample(sid);
                if (mysig == null)
                {
                    mysig = new Sig();
                }
                if (ModMain.loadsignew(ref mysig, sid))
                {
                    showcurSig();
                }
                else
                {
                    mcurve1.reset();
                }
                //return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        public void setlineColor()
        {
            Color c=ModMain.getChanelColor("C");
            mcurve1.setlinecolor(0, c);
            this.label6.BackColor = c;
            c = ModMain.getChanelColor("S");
            mcurve1.setlinecolor(1, c);
            this.label8.BackColor = c;
            c = ModMain.getChanelColor("C2");
            mcurve1.setlinecolor(2, c);
            this.label10.BackColor = c;
            c = ModMain.getChanelColor("S2");
            mcurve1.setlinecolor(3, c);
            this.label12.BackColor = c;
        }
        public void lineEnable(ref double[] ytmp, ref int n, double lineXishu)
        {
            try
            {
                int i = 0;
                for (i = 0; i <= n - 1; i++)
                {
                    ytmp[i] = ytmp[i] * System.Math.Exp(ytmp[i] / lineXishu);
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        public bool calcArea(int id, string ele, ref double eleArea)
        {
            bool functionReturnValue = false;
            calcId(id);
            functionReturnValue = true;
            if (ele == "C" | ele == "C2")
            {
                eleArea = sample1.cArea;
            }
            else
            {
                eleArea = sample1.sArea;
            }
            return functionReturnValue;
        }
        public void calcId(int id)
        {
            if (ModMain.method1 == null)
                return;
            loadSample(id);
            if (ModMain.loadsignew(ref mysig, id))
            {
                calcAll(true);
            }
            else
            {
                calcAll(false);
            }
        }





        public void calcAll(bool calcArea)
        {
            if (ModMain.getChanelEnable("C") == true & ModMain.getChanelEnable("C2") == true)
            {

                if (mysig.getstoped(0))//C2
                {
                    sample1.isHc = -1;
                    calcOne(2, calcArea);
                }
                else//C
                {
                    sample1.isHc = 0;
                    calcOne(0, calcArea);
                }
            }
            else if (ModMain.getChanelEnable("C") == true)//C
            {
                sample1.isHc = 0;
                calcOne(0, calcArea);
            }
            else if (ModMain.getChanelEnable("C2") == true)//C2
            {
                sample1.isHc = -1;
                calcOne(2, calcArea);
            }
            else//no c
            {
                sample1.isHc = 1;
            }
            if (ModMain.getChanelEnable("S") == true & ModMain.getChanelEnable("S2") == true)
            {

                if (mysig.getstoped(1))//S2
                {
                    sample1.isHs = -1;
                    calcOne(3, calcArea);
                }
                else//S
                {
                    sample1.isHs = 0;
                    calcOne(1, calcArea);
                }
            }
            else if (ModMain.getChanelEnable("S") == true)//S
            {
                sample1.isHs = 0;
                calcOne(1, calcArea);
            }
            else if (ModMain.getChanelEnable("S2") == true)//S2
            {
                sample1.isHs = -1;
                calcOne(3, calcArea);
            }
            else//no S
            {
                sample1.isHs = 1;
            }
        }

        public void calcOne(int chanel, bool calcarea)
        {
            NCS.curveXishu e = null;
            e = null;
            double wlConc = 0;
            double bjsp = 0;
            double panju = 0;
            switch (chanel)
            {
                case 0:
                    e = ModMain.getChanelxishu("C");
                    wlConc = ModMain.method1.wlC;
                    bjsp = e.bjsp;
                    panju = e.panju;
                    break;
                case 1:
                    e = ModMain.getChanelxishu("S");
                    wlConc = ModMain.method1.wlS;
                    bjsp = e.bjsp;
                    panju = e.panju;

                    break;
                case 2:
                    e = ModMain.getChanelxishu("C2");
                    bjsp = e.bjsp;
                    panju = e.panju;
                    wlConc = ModMain.method1.wlC;

                    break;
                case 3:
                    e = ModMain.getChanelxishu("S2");
                    wlConc = ModMain.method1.wlS;
                    bjsp = e.bjsp;
                    panju = e.panju;

                    break;
            }
            if (e == null)
                return;
            if (calcarea)
            {
                double[] xtmp = null;
                double[] ytmp = null;
                int n = 0;
                xtmp =(double[]) mysig.getarr().Clone();
                ytmp =(double[]) mysig.getArr(chanel).Clone();

                n = mysig.xn;

                if (e.LINExishu == 0)
                {
                    // 线性化
                }
                else
                {
                    lineEnable(ref ytmp, ref n, e.LINExishu);
                }
                ModMain.KouJIxian(ref xtmp, ref ytmp, ref n);
                jf1.setArr(ref xtmp, ref ytmp, n);
                jf1.calcZeroRand();
                //jf1.setRand(mRand);
                //用平滑前的噪声
                switch (chanel)
                {
                    case 0:
                        sample1.cArea = System.Math.Abs(jf1.getjfvalueNew(bjsp, panju));
                        sample1.cIndex = jf1.first;
                        sample1.cIndex2 = jf1.last;
                        break;
                    case 1:
                        sample1.sArea = System.Math.Abs(jf1.getjfvalueNew(bjsp, panju));
                        sample1.sIndex = jf1.first;
                        sample1.sIndex2 = jf1.last;
                        break;
                    case 2:
                        sample1.cArea = System.Math.Abs(jf1.getjfvalueNew(bjsp, panju));
                        sample1.cIndex = jf1.first;
                        sample1.cIndex2 = jf1.last;
                        break;
                    case 3:
                        sample1.sArea = System.Math.Abs(jf1.getjfvalueNew(bjsp, panju));
                        sample1.sIndex = jf1.first;
                        sample1.sIndex2 = jf1.last;
                        break;
                }
            }//calc area
            
            switch (chanel)
            {
                case 0:
                    sample1.c = ecalcConc(e, sample1.cArea, sample1.weight, sample1.wlweight * wlConc, 0);
                    break;
                case 1:
                    sample1.s = ecalcConc(e, sample1.sArea, sample1.weight, sample1.wlweight * wlConc, sample1.c);
                    break;
                case 2:
                    sample1.c = ecalcConc(e, sample1.cArea, sample1.weight, sample1.wlweight * wlConc, 0);
                    break;
                case 3:
                    sample1.s = ecalcConc(e, sample1.sArea, sample1.weight, sample1.wlweight * wlConc, sample1.c);
                    break;
            }
        }

        public void getINArr(ref double[] a, int b, int b2, ref double[] a2)
        {
            a2 = new double[b2 - b + 1];
            int i = 0;
            for (i = 0; i <= b2 - b; i++)
            {
                a2[i] = a[b + i];
            }
        }
        public void showcurSig()
        {
            try
            {
                showcurSigonly();
                showcurRegion();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }


        public void settp(int id)
        {
            ctp1.setTp(id);
        }


        private void DataGrid1_CellClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            //this.showcur();
        }


        private void Check2_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            //when set check value, it call this sub
            //If busy Then Exit Sub
            bool b;
            if (Check2.CheckState == CheckState.Checked)
                b = true;
            else
                b = false;
            mcurve1.setlinevisible(0, b);
            mcurve1.setlinevisible(0 + ModMain.NUMChanel, b);
            mcurve1.fit();
        }

        private void Check3_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            bool b;
            if (Check3.CheckState == CheckState.Checked)
                b = true;
            else
                b = false;
            mcurve1.setlinevisible(1, b);
            mcurve1.setlinevisible(1 + ModMain.NUMChanel, b);
            mcurve1.fit();
        }

        private void Check4_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            bool b;
            if (Check4.CheckState == CheckState.Checked)
                b = true;
            else
                b = false;
            mcurve1.setlinevisible(2, b);
            mcurve1.setlinevisible(2 + ModMain.NUMChanel, b);
            mcurve1.fit();
        }

        private void Check5_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            bool b;
            if (Check5.CheckState == CheckState.Checked)
                b = true;
            else
                b = false;

            mcurve1.setlinevisible(3, b);
            mcurve1.setlinevisible(3 + ModMain.NUMChanel, b);
            mcurve1.fit();
        }


        private void DataGrid1_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
        }



        private void DataGrid2_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
        }

        private void showCurve_Click(System.Object sender, System.EventArgs e)
        {
            showcurSigRaw();
        }

        private void 标样ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            FrmStandard fm = new FrmStandard();
            fm.ShowDialog();
        }

        private void TextSampleWeight_Click1(object sender, System.EventArgs e)
        {
            this.TextSampleWeight.SelectAll();
        }


        private void TextSampleWeight_TextChanged(System.Object sender, System.EventArgs e)
        {
        }


        private void SplitContainer1_SplitterMoved(System.Object sender, System.Windows.Forms.SplitterEventArgs e)
        {
        }




        private void DataGrid1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
        {
            // If the column being formatted is the column named 'Status' ..
            try
            {
                //Debug.Print(Me.DataGrid1.Columns[e.ColumnIndex).Name)
                if (this.DataGrid1.Columns[e.ColumnIndex].Name == "c")
                {
                    if (this.DataGrid1.Rows[e.RowIndex] == null)
                        return;

                    if ((int)this.DataGrid1.Rows[e.RowIndex].Cells["ishc"].Value == -1)
                    {

                        e.CellStyle.BackColor = Color.FromArgb(128, 128, 128);

                    }
                    else if ((int)this.DataGrid1.Rows[e.RowIndex].Cells["ishc"].Value == 0)
                    {
                        e.CellStyle.BackColor = Color.FromArgb(255, 255, 255);

                    }
                    e.Value = string.Format("{0:F5}", e.Value);
                }


                if (this.DataGrid1.Columns[e.ColumnIndex].Name == "s")
                {
                    if (this.DataGrid1.Rows[e.RowIndex] == null)
                        return;

                    if ((int)this.DataGrid1.Rows[e.RowIndex].Cells["ishs"].Value == -1)
                    {

                        // Set the BackColor of the cell to yellow.

                        e.CellStyle.BackColor = Color.FromArgb(200, 200, 0);
                    }
                    else if ((int)this.DataGrid1.Rows[e.RowIndex].Cells["ishs"].Value == 0)
                    {
                        e.CellStyle.BackColor = Color.FromArgb(255, 255, 255);

                    }
                    e.Value = string.Format("{0:F5}", e.Value);
                }
            }
            catch (Exception e1)
            {
                modLog.savelogmsg(e1.ToString());
            }

        }

        private void DataGrid1_CellMouseDoubleClick(object sender, System.Windows.Forms.DataGridViewCellMouseEventArgs e)
        {
            System.Windows.Forms.DataGridViewRow r = null;
            r = DataGrid1.CurrentRow;
            if (r == null)
                return;
            //try
            //{
                int sid = 0;
                sid = (int)r.Cells["id"].Value;
                this.showcurveOne(sid);
            //}
            //catch (System.InvalidCastException e1)
            //{
            //    modLog.savelogmsg(e1.ToString());
            //}
        }


        private void DataGrid1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
        {
        }
        private void btnPrintPreview_Click(DataGridView d)
        {
            if (SetupThePrinting(ref d))
            {
                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
                MyPrintPreviewDialog.Document = PrintDocument1;
                MyPrintPreviewDialog.ShowDialog();
            }
        }

        private bool SetupThePrinting(ref DataGridView d)
        {
            //PrintDialog MyPrintDialog = new PrintDialog();
            //MyPrintDialog.AllowCurrentPage = false;
            //MyPrintDialog.AllowPrintToFile = false;
            //MyPrintDialog.AllowSelection = false;
            //MyPrintDialog.AllowSomePages = false;
            //MyPrintDialog.PrintToFile = false;
            //MyPrintDialog.ShowHelp = false;
            //MyPrintDialog.ShowNetwork = false;
            //MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape = true;
            //if (MyPrintDialog.ShowDialog() != DialogResult.OK)
            //{
            //    return false;
            //}

            //PrintDocument1.DocumentName = "Customers Report";
            //PrintDocument1.PrinterSettings = MyPrintDialog.PrinterSettings;

            //PrintDocument1.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
            //PrintDocument1.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);

            ////If MessageBox.Show.Show("Do you want the report to be centered on the page", "InvoiceManager - Center on Page", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            //datagrid1Printer = new DataGridViewPrinter(d, PrintDocument1, true, true, "NCS_CS分析结果", new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
            ////Else
            ////    datagrid1Printer = New DataGridViewPrinter(DataGrid1, PrintDocument1, False, True, "Customers", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), _
            ////     Color.Black, True)
            ////End If

            return true;
        }

        private void PrintDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //bool more = this.datagrid1Printer.DrawDataGridView(e.Graphics);
            //if (more == true)
            //{
            //    e.HasMorePages = true;
            //}
        }
        public double ecalcConc(NCS.curveXishu chanelXishu, double eleArea, double wt, double wlwt, double oconc)
        {
            double m = 0;
            double res = 0;
            double area = 0;
            if (ModMain.buChuCO2 && (chanelXishu.ele == "S" || chanelXishu.ele == "S2"))
            {
                area = eleArea - chanelXishu.ln * wt * oconc;
            }
            else
            {
                area = eleArea;
            }
            m = area * chanelXishu.x1 + chanelXishu.x0;
            res = (m - wlwt) / wt;
            return res;
        }

        private void mnuShowAVe_Click(System.Object sender, System.EventArgs e)
        {
            if (mnuShowAVe.CheckState == CheckState.Checked)
            {
                this.SplitContainer_result.Panel2Collapsed = false;
            }
            else
            {
                this.SplitContainer_result.Panel2Collapsed = true;
            }
        }

        private void 时序ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            this.Visible = false;
            FormShixu fm = new FormShixu();
            fm.ShowDialog();
            this.Visible = true;
        }
        public void showcurRegion()
        {
            if (sample1.isHc == -1)
            {
                Check4.CheckState = System.Windows.Forms.CheckState.Checked;
                Check2.CheckState = System.Windows.Forms.CheckState.Unchecked;
                mcurve1.setlinevisible(2, true);
                mcurve1.setlinevisible(0, false);
            }
            else if (sample1.isHc == 0)
            {
                Check4.CheckState = System.Windows.Forms.CheckState.Unchecked;
                Check2.CheckState = System.Windows.Forms.CheckState.Checked;
                mcurve1.setlinevisible(2, false);
                mcurve1.setlinevisible(0, true);
            }
            else
            {
                Check4.CheckState = System.Windows.Forms.CheckState.Unchecked;
                Check2.CheckState = System.Windows.Forms.CheckState.Unchecked;
                mcurve1.setlinevisible(2, false);
                mcurve1.setlinevisible(0, false);
            }
            if (sample1.isHs == -1)
            {
                Check5.CheckState = System.Windows.Forms.CheckState.Checked;
                Check3.CheckState = System.Windows.Forms.CheckState.Unchecked;
                mcurve1.setlinevisible(3, true);
                mcurve1.setlinevisible(1, false);
            }
            else if (sample1.isHs == 0)
            {
                Check3.CheckState = System.Windows.Forms.CheckState.Checked;
                Check5.CheckState = System.Windows.Forms.CheckState.Unchecked;
                mcurve1.setlinevisible(3, false);
                mcurve1.setlinevisible(1, true);
            }
            else
            {
                Check3.CheckState = System.Windows.Forms.CheckState.Unchecked;
                Check5.CheckState = System.Windows.Forms.CheckState.Unchecked;
                mcurve1.setlinevisible(3, false);
                mcurve1.setlinevisible(1, false);
            }

            if (Check7.CheckState == CheckState.Checked)
            {
                if (sample1.isHc == -1)
                {
                    mcurve1.setregion(sample1.cIndex, sample1.cIndex2, 2);
                }
                else if (sample1.isHc == 0)
                {
                    mcurve1.setregion(sample1.cIndex, sample1.cIndex2, 0);
                }
                if (sample1.isHs == -1)
                {
                    mcurve1.setregion(sample1.sIndex, sample1.sIndex2, 3);
                }
                else if (sample1.isHs == 0)
                {
                    mcurve1.setregion(sample1.sIndex, sample1.sIndex2, 1);
                }
            }
            mcurve1.fit();

        }
        public void RunScript(string name)
        {
            //MessageBox.Show.Show("add code here to run " + name);
            //try
            //{
                ModMain.m_python.ExecuteFile(name,ModMain.gscope);
            //}
            //catch (System.Exception e)
            //{ 
            //}
        }
        private void RunScriptToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = modLog.initpath;
            ofd.Filter = "python files (*.py)|*.py|All files (*.*)|*.*";
            ofd.FilterIndex = 1;
            if ((ofd.ShowDialog() == DialogResult.OK))
            {
                RunScript(ofd.FileName);
            }
        }
        public void showcurSigonly()
        {
            try
            {
                //Dim xtmp2 As Single()
                //Dim ytmp2 As Single()

                mcurve1.init();
                mcurve1.setLineCount(4);
                setlineColor();
                double[] xtmp = null;
                double[] ytmp = null;
                int n = 0;
                int i = 0;
                for (i = 0; i <= ModMain.NUMChanel - 1; i++)
                {
                    xtmp = mysig.getarr();
                    ytmp = mysig.getArr(i);
                    n = mysig.xn;
                    ModMain.KouJIxian(ref xtmp, ref ytmp, ref n);
                    mcurve1.setArrV(ref xtmp, ref  ytmp, n, i);

                }
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        public void showcurSigRaw()
        {
            try
            {
                showcurSigRawonly();
                showcurRegion();

            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }



        private void DataGrid1_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
        }

        private void DataGrid1_RowEnter(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            Debug.Print("row enter");
            DataGridViewRow r = null;
            r = DataGrid1.Rows[e.RowIndex];
            int sid = 0;
            sid = (int)r.Cells["sampleid"].Value;
            refreshSelAveOld(sid);

            //System.Windows.Forms.DataGridViewRow r = null;
            //r = DataGrid1.CurrentRow;
            //if (r == null)
            //    return;
            try
            {
                //int sid = 0;
                sid = (int)r.Cells["id"].Value;
                this.showcurveOne(sid);
            }
            catch (System.InvalidCastException e1)
            {
                modLog.savelogmsg(e1.ToString());
            }
        }


        private void TableLayoutPanel2_Paint(System.Object sender, System.Windows.Forms.PaintEventArgs e)
        {
        }

        private void csy1_FinishSIG(object Sender, Mcsy.sigFinishEventArgs e)
        {
            bool cstop = false;
            bool sstop = false;
            cstop = mysig.getstoped(0);
            sstop = mysig.getstoped(1);
            modLog.savelogmsg("cstop" + Convert.ToString(cstop));
            modLog.savelogmsg("sstop" + Convert.ToString(sstop));
            mysig = e.s;
            mysig.setstoped(0, cstop);
            mysig.setstoped(1, sstop);
            calcAll(true);
            record();  //save data
            this.TextSampleWeight.Text = "0.0000";
            this.Text4.Text = "0.0000";
            reset_Renamed();
            this.showcurSig();
        }


        private void StartToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            this.CommandStart_Click(null, null);

        }

        private void StopToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            this.CommandStop_Click(null, null);
        }

        private void 原始曲线ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            System.Windows.Forms.DataGridViewRow r = null;
            r = DataGrid1.CurrentRow;
            if (r == null)
                return;
            try
            {
                int sid = 0;
                sid = Convert.ToInt32(r.Cells["id"].Value);
                loadSample(sid);
                if (ModMain.loadsignew(ref mysig, sid))
                {
                    showcurSigRaw();
                }
                return;
            }
            catch (System.InvalidCastException e1)
            {
                modLog.savelogmsg(e1.ToString());
            }
        }
        public void showcurSigRawonly()
        {
            try
            {
                //Dim xtmp2 As Single()
                //Dim ytmp2 As Single()

                mcurve1.init();
                mcurve1.setLineCount(ModMain.NUMChanel);
                setlineColor();
                double[] xtmp;
                double[] ytmp;
                int n = 0;
                int i = 0;
                for (i = 0; i <= ModMain.NUMChanel - 1; i++)
                {
                    xtmp = mysig.getarr();
                    ytmp = mysig.getArr(i);
                    n = mysig.xn;
                    mcurve1.setArrV(ref xtmp, ref  ytmp, n, Convert.ToInt16(i));

                }
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        private void csy1_EVpower(object Sender, Mcsy.EVpowerEventArgs e)
        {
            double x = e.x;
            double y = e.y;
            y = y / 6000 * 5;
            //if (firstp)
            //{
            //    mcurve1.starttmpline(x, y, 4);
            //    firstp = false;
            //}
            //else
            //{
                mcurve1.tmplineaddpoint(x, y, 4);
            //}
        }


        private void csy1_evReset(object Sender, System.EventArgs e)
        {
        }
        private void csy1_myStatus(object Sender, Mcsy.myStatusEventArgs e)
        {
            this.label_volt.Text = string.Format("{0:F1}", e.u); //e.v;
            this.label_current.Text = string.Format("{0:F0}", e.v); //e.v;
            this.label_power.Text = string.Format("{0:F0}", e.u * e.v); //e.v;
            this.label_jinghua.Text = string.Format("{0:F0}", e.jh);// e.jh;
            this.label_zhuanhua.Text = string.Format("{0:F0}", e.zh); //e.v;
            this.label_shuiwen.Text = string.Format("{0:F0}", e.sw);// e.jh;
        }
        private void csy1_startTask(object Sender, Mcsy.startTaskEventArgs e)
        {
            //          Me.sbStatusBar.Panels("state").Text = "running"
            //Me.sbStatusBar.Panels("state").Text = Me.sbStatusBar.Panels("state").Text + Str(id)
            //savelogmsg "start task" + Str(id)
            //curTask = id
            CommandStart.Enabled = false;
            CommandStop.Enabled = true;
        }
        private void csy1_StatusStr(object Sender, Mcsy.StatusStrEventArgs e)
        {
            stateStatus.Text = e.s;
        }
        private void csy1_endTask(object Sender, Mcsy.endTaskEventArgs e)
        {
            //Me.sbStatusBar.Panels("state").Text = gtran.MyTranslate("准备好", "ready")
            modLog.savelogmsg("end all task");
            //if( csy1.isYuchuli)
            //{
            //    csy1.isYuchuli = false;
            //    csy1.stopYUchuli();
            //    csy1.setState( 3);
            //}
            //csy1.isShouDong = false;
            CommandStart.Enabled = true;
            CommandStop.Enabled = false;
        }

        private void _Toolbar1_Button6_Click(object sender, EventArgs e)
        {
            csy1.jiayang();
        }

        private void _Toolbar1_Button1_Click(object sender, EventArgs e)
        {
            showfrmMethod();
        }

        private void _Toolbar1_Button8_Click(object sender, EventArgs e)
        {
            mnuClear_Click(mnuClear, new System.EventArgs());
        }

        private void _Toolbar1_Button2_Click(object sender, EventArgs e)
        {
            mnuTestBaseline_Click(mnuTestBaseline, new System.EventArgs());
        }

        private void _Toolbar1_Button4_Click(object sender, EventArgs e)
        {
            delrec();
        }

        private void _Toolbar1_Button5_Click(object sender, EventArgs e)
        {
            avgrec();
        }

        private void _Toolbar1_Button7_Click(object sender, EventArgs e)
        {
            csy1.reverseFurnace();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult v;
            v = MessageBox.Show("确实退出？", "", MessageBoxButtons.YesNo);
            if (v == DialogResult.Yes)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }


        private void importDb4oToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Db4objects.Db4o.IObjectContainer db = null;
            db = Db4objects.Db4o.Db4oFactory.OpenFile(modLog.initpath + "\\volt2.data");
            Db4objects.Db4o.Query.IQuery query = db.Query();
            query.Constrain(typeof(Sig));
            //query.Descend("sampleid").Constrain(sid);
            Db4objects.Db4o.IObjectSet o = null;
            o = query.Execute();
            //Sig sig1;
            foreach (Sig sig1 in o)
            {
                Debug.Print(sig1.sampleid.ToString());
                sig1.save(sig1.sampleid );
                //Debug.Print("save finish");
                //System.Diagnostics.Debugger.
                
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            toolStripButton1.Checked = !toolStripButton1.Checked;// !true;
            if (toolStripButton1.Checked)
            {
                toolStripButton1.Image = NCS_CS.Properties.Resources.节气 ;
                toolStripButton1.Text = "节气";
                csy1.jieqi();
            }
            else
            {
                toolStripButton1.Image = NCS_CS.Properties.Resources.workqi  ;
                toolStripButton1.Text = "不节气";
                csy1.workQi();
            }
            //csy1.setJieQi(toolStripButton1.Checked);
        }

        private void mcurve1_DoubleClick(object sender, EventArgs e)
        {
            //FormZed f = new FormZed();
            //f.ShowDialog();
            
        }

        private void mnuContrastPh_Click(object sender, EventArgs e)
        {
            int i = 0;
            Sig[] sigs = null;
            System.Collections.ArrayList sid;
            sid = new System.Collections.ArrayList();
            frmSelectChanel fm;
            if (DataGrid1.SelectedRows.Count > 0)
            {
                fm = new frmSelectChanel();
                fm.ShowDialog();
                if (!fm.confirm)
                    return;
            }
            else
            {
                MessageBox.Show("请选择单次数据", "");
                return;
            }
            int chanel_Renamed = 0;
            chanel_Renamed = fm.the;
            int id = 0;
            foreach (System.Windows.Forms.DataGridViewRow b in DataGrid1.SelectedRows)
            {
                id = (int)b.Cells["id"].Value;
                sid.Add(id);
            }
            sigs = new Sig[sid.Count];
            foreach (int c in sid)
            {
                sigs[i] = new Sig();
                ModMain.loadsignew(ref sigs[i], c);
                i++;
            }
            mcurve1.clear();
            mcurve1.setLineCount(Convert.ToInt16(sid.Count));
            try
            {
                for (i = 0; i < sid.Count; i++)
                {
                    sigs[i].mcurveSetarrvPH(ref mcurve1, chanel_Renamed, i);
                }
                mcurve1.fit();
            }
            catch (System.NullReferenceException e1)
            {
                modLog.savelogmsg(e1.ToString());
            }
        }

        private void csy1_EVjieQi(object Sender, Mcsy.StatusJieQiEventArgs e)
        {
            if (e.b)
            {
                toolStripButton1.Checked = true;
                    toolStripButton1.Image = NCS_CS.Properties.Resources.节气 ;
                    toolStripButton1.Text = "节气";
            }
            else
            {
                toolStripButton1.Checked = false;
                toolStripButton1.Image = NCS_CS.Properties.Resources.workqi;
                toolStripButton1.Text = "不节气";

            }
        }

        private void label6_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog();
            if (DialogResult.OK != cd.ShowDialog())
            { }
            else
            {
                 ModMain.gchanelDic["C"].color =cd.Color.ToArgb()  ;
                this.label6.BackColor = cd.Color ;
                ISession s = ModMain.getsession();
                s.Update(ModMain.gchanelDic["C"]);
                s.Flush();
            }

        }

        private void label8_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog();
            if (DialogResult.OK != cd.ShowDialog())
            { }
            else
            {
                ModMain.gchanelDic["S"].color = cd.Color.ToArgb();
                this.label8.BackColor = cd.Color;
                ISession s = ModMain.getsession();
                s.Update(ModMain.gchanelDic["S"]);
                s.Flush();
            }

        }

        private void label10_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog();
            if (DialogResult.OK != cd.ShowDialog())
            { }
            else
            {
                ModMain.gchanelDic["C2"].color = cd.Color.ToArgb();
                this.label10.BackColor = cd.Color;
                ISession s = ModMain.getsession();
                s.Update(ModMain.gchanelDic["C2"]);
                s.Flush();
            }
        }

        private void label12_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog();
            if (DialogResult.OK != cd.ShowDialog())
            { }
            else
            {
                ModMain.gchanelDic["S2"].color = cd.Color.ToArgb();
                this.label12.BackColor = cd.Color;
                ISession s = ModMain.getsession();
                s.Update(ModMain.gchanelDic["S2"]);
                s.Flush();
            }
        }

    }
}
